package com.andy.wang.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;

import java.io.ByteArrayInputStream;

import static com.qcloud.cos.demo.ci.ClientUtils.getCosClient;
public class UploadFile {
    public static String uploadFile(byte[] bytes, String fileName) {
        String backUrl = "";
        // String bucket = BUCKETNAME + "-" + APPID;
         String bucket="test01-1324045941";
//        System.out.println("test01-1324045941");
        String key = "test/" + fileName;

        ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setContentType("image/jpeg");

        metadata.setContentLength(bytes.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, new ByteArrayInputStream(bytes),
                metadata);

        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);
        COSClient cc = getCosClient("AKID00ra7TehYHuOfOvKWUSNByZ2MYYQBzkH","jU6by9C3h8VvIUjEpGamt4gDmQvUzNYY","ap-beijing");
        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            backUrl = "https://test01-1324045941.cos.ap-beijing.myqcloud.com" + "/" + key;
            System.out.println(backUrl);
            return backUrl;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cc.shutdown();
        return backUrl;
    }
}
